<?php
namespace App\Http\Controllers\Entity\Assets;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Assets\AssetsRequest;
use App\Http\Requests\Entity\Assets\AssetStreamRequest;
use App\Models\Entity\Assets\Assets;
use App\Models\Entity\Assets\AssetStream;
use App\Models\Import\BatchImportVassetiHistory;
use App\Models\Injection\InjectAssetiHistory;
use App\Models\Common\EntityData\Channel\Sp;
use App\Repositories\Entity\Assets\AssetsRepository;
use App\Repositories\Entity\Assets\AssetStreamRepository;
use App\Classes\Injection\AssetiInjection;
use App\Classes\Injection\importCms;
use App\Jobs\Injection\AssetiInjectionJob;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Excel;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
//校验
use SebastianBergmann\Diff\Exception;
use Validator;
use Auth;
use DB;
use Illuminate\Support\MessageBag;


class AssetStreamsController extends Controller
{
    use ModelForm;

    /** @var  AssetsRepository */
    private $AssetStreamRepository;

    public function __construct(AssetStreamRepository $AssetStreamRepo)
    {
        $this->AssetStreamRepository = $AssetStreamRepo;
    }

    /**
     * Display a listing of the Assets.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('视频流');
            $content->description(__('entity.assets.assets.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Assets.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('视频流');
            $content->description(__('entity.assets.assets.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Assets in storage.
     *
     * @param AssetsRequest $request
     *
     * @return Response
     */
    public function store(AssetsRequest $request)
    {
        $input  = $request->all();
        $assets = $this->assetsRepository->create($input);


        Flash::success(__('entity.assets.assets.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.assets.assets.index'));

    }

    /**
     * Display the specified Assets.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $assets = $this->assetsRepository->findWithoutFail($id);

        if (empty($assets)) {
            Flash::error(__('entity.assets.assets.not_found'));

            return redirect(route('entity.assets.assets.index'));
        }

        return view('entity.assets.assets.show')->with('assets', $assets);

    }

    /**
     * Show the form for editing the specified Assets.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {


        return Admin::content(function (Content $content) use ($id) {

            $content->header('视频流');
            $content->description('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Assets in storage.
     *
     * @param  int $id
     * @param AssetsRequest $request
     *
     * @return Response
     */
    public function update($id, AssetsRequest $request)
    {
        $assets = $this->assetsRepository->findWithoutFail($id);

        if (empty($assets)) {
            Flash::error(__('entity.assets.assets.not_found'));

            return redirect(route('entity.assets.assets.index'));
        }
        $input = $request->all();

        //更新媒资基本数据
        $assets = $this->assetsRepository->update($input, $id);

        //更新媒资渠道方信息
        AssetStream::where('asset_id', $id)->update($input['stream']);


        Flash::success(__('entity.assets.assets.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.assets.assets.index'));
    }

    /**
     * Remove the specified Assets from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->assetsRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('entity.assets.assets.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $assets = $this->assetsRepository->findWithoutFail($id);

        if (empty($assets)) {
            Flash::error(__('entity.assets.assets.not_found'));

            return redirect(route('entity.assets.assets.index'));
        }

        if ($flag = $this->assetsRepository->delete($id)) {
            return response()->json(['message' => __('entity.assets.assets.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(AssetStream::class, function (Form $form) {

            //$form->display('id', 'ID');
            $form->text('asset.title', '名称/标题');
            $form->text('asset.subtitle', '副标题');
            $form->textarea('asset.short_desc', '简介');
            $form->textarea('asset.long_desc', '介绍');
            $form->text('asset.inject_datetime', '注入完成时间');
            $form->text('ogroup_asset_id', '渠道方媒资ID');
            $form->text('stream_id', '注入流ID');
            $form->text('cdn_id', '注入目标');
            $form->json('ogroup_asset_data', '渠道方媒资数据');
            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

//
    protected function grid(){
        return Admin::grid(AssetStream::class, function (Grid $grid) {

            // 添加按钮
            if (Admin::user()->cannot('entity.assets.assets.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.assets.assets.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.assets.assets.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.assets.assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {

                $url =  route('entity.assets.assets.model',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');

                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.assets.assets.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('asset.id', '媒资ID')->sortable();
            $grid->column('asset.title', '媒资名/标题')->sortable();
            $grid->column('asset.spasset_id', 'SP 媒资 ID')->sortable();
            $grid->column('ogroup_asset_id', '渠道 媒资 ID');
            $grid->column('stream_id', '渠道媒资流 ID');
            $grid->column('cdn_id', '渠道CDN ID');

            $grid->column('asset.inject_datetime', '注入完成时间')->sortable()->display(function ($val) {
                if(!empty($val))
                    return date("Y-m-d H:i",$val);
                else return '';
            });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                $filter->disableIdFilter();
                $filter->equal('asset_id', '主媒资ID');
                $filter->equal('stream_id', '注入流ID');
                $filter->equal('ogroup_asset_id', '渠道方 媒资 ID');
                $filter->equal('cdn_id', '注入目标');

            });
        });
    }
}